﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PelitaProduksi.Controller
{
    class MySQLController
    {
        MySqlConnection con;
        string server, dbName, user, pass, port;
        public MySQLController()
        {
            initData();
            con = new MySqlConnection(string.Format
                ("server={0};database={1};uid={2};pwd={3};port={4}", 
                server, dbName, user, pass, port));
        }
        private void initData()
        {
            string[] lines = System.IO.File.ReadAllLines("Setting/Setting.txt");
            foreach (string line in lines)
            {
                string[] temp = line.Split('\t');
                if (temp == null || temp.Length != 2) continue;
                switch (temp[0])
                {
                    case "server":
                        server = temp[1];
                        break;
                    case "dbname":
                        dbName = temp[1];
                        break;
                    case "dbuser":
                        user = temp[1];
                        break;
                    case "dbpass":
                        pass = temp[1];
                        break;
                    case "dbport":
                        port = temp[1];
                        break;
                }
            }
        }
        public void Open()
        {
            con.Open();
        }
        public void Close()
        {
            con.Close();
        }
        ~MySQLController()
        {
            Close();
        }
        public MySqlTransaction BeginTransaction()
        {
            MySqlTransaction transaction = con.BeginTransaction();
            return transaction;
        }
        public MySqlDataReader ExecuteReader(string query)
        {
            MySqlCommand cmd = new MySqlCommand(query);
            cmd.Connection = con;
            return cmd.ExecuteReader();
        }
        public object ExecuteScalar(string query)
        {
            MySqlCommand cmd = new MySqlCommand(query);
            cmd.Connection = con;
            return cmd.ExecuteScalar();
        }
        public void ExecuteNonQuery(string query)
        {
            MySqlCommand cmd = new MySqlCommand(query);
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
        }
    }
}
